module ctrl (
    input                           clk,rstn,
    output      reg     [2:0]       ew,sn       //g,y,r
);

parameter s0 = 2'b00;
parameter s1 = 2'b01;
parameter s2 = 2'b10;
parameter s3 = 2'b11;
parameter IDLE = 2'bZZ;
reg [3:0]   count;
reg [1:0]   prestate,nxtstate;
reg         flag;

//状态转换
always @(flag or rstn) begin
    if (!rstn) begin
        prestate <= IDLE;
    end else begin
        prestate <= nxtstate;
    end
end

//下一状态
always @(flag) begin
    case (prestate)
        IDLE: nxtstate <= s0;
        s0: nxtstate <= s1;
        s1: nxtstate <= s2;
        s2: nxtstate <= s3;
        s3: nxtstate <= s1;
        default: nxtstate <= IDLE;
    endcase
end

//输出
always @(prestate) begin
    case (prestate)
        IDLE: begin
            ew <= 3'bZZZ;
            sn <= 3'bZZZ;
        end 
        s0: begin
            ew <= 3'b100;
            sn <= 3'b001;
        end 
        s1: begin
            ew <= 3'b010;
            sn <= 3'b001;
        end 
        s2: begin
            ew <= 3'b001;
            sn <= 3'b100;
        end 
        s3: begin
            ew <= 3'b001;
            sn <= 3'b010;
        end 
        default: begin
            ew <= 3'bZZZ;
            sn <= 3'bZZZ;
        end 
    endcase
end

//flag产生
always @(posedge clk ) begin
    if (!rstn) begin
            flag <= 0;
        end else begin
            flag <= 1;
    if (prestate == IDLE) begin
        if (!rstn) begin
            flag <= 0;
        end else begin
            flag <= 1;
        end 
    end else if (flag) begin
        flag <= 0;
        count <= 1;
    end else begin
        case (count)
            4: begin
                if ((prestate == s1) || (prestate == s3)) begin
                    flag <= 1;
                    count <= 0;
                end else begin
                    count <= count + 1;
                end
            end
            9: begin
                flag <= 1;
                count <= 0;
            end
            default: count <= count + 1;
        endcase
    end
    end 
end
endmodule //ctrl